import { defineStore } from "pinia";
import { store } from "@/store";
import { getStore, setStore } from "@/utils/localStorage";
import { getConfig } from "@/config/index";
import { deviceDetection } from "@/utils/validate";

export const useAppStore = defineStore({
  id: "app-store",
  state: () => ({
    sidebar: {
      opened: getStore({ name: "layout" })?.sidebarStatus ?? getConfig().SidebarStatus,
      withoutAnimation: false,
      isClickCollapse: false
    },
    layout: getStore({ name: "layout" })?.layout ?? getConfig().Layout,
    device: deviceDetection() ? "mobile" : "desktop"
  }),
  getters: {},
  actions: {
    toggleCollapse(opened?: boolean, resize?: string) {
      const layout = getStore({ name: "layout" });
      if (opened && resize) {
        this.sidebar.withoutAnimation = true;
        this.sidebar.opened = true;
        layout.sidebarStatus = true;
      } else if (!opened && resize) {
        this.sidebar.withoutAnimation = true;
        this.sidebar.opened = false;
        layout.sidebarStatus = false;
      } else if (!opened && !resize) {
        this.sidebar.withoutAnimation = false;
        this.sidebar.opened = !this.sidebar.opened;
        this.sidebar.isClickCollapse = !this.sidebar.opened;
        layout.sidebarStatus = this.sidebar.opened;
      }
      setStore({ name: "layout", content: layout });
    },
    toggleDevice(device: string) {
      this.device = device;
    },
    setLayout(layout) {
      this.layout = layout;
    }
  }
});

export function useAppStoreHook() {
  return useAppStore(store);
}
